package com.hjt.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign调用的配置，feign远程调用时，会创建一个新的request，然后使用容器中的RequestInterceptor进行拦截增强
 * @author:97007
 * @date:2021/10/9 20:20
 */
@Configuration
public class OrderFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        // 使用自定义的请求拦截器给feign远程调用请求设置cookie
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 1.使用RequestContextHolder获取进来的请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    HttpServletRequest request = requestAttributes.getRequest();
                    // 同步请求数据
                    requestTemplate.header("Cookie", request.getHeader("Cookie"));
                }
            }
        };
    }
}
